<?php
	/**
	 * @Authot leeio(http://leeiio.me)
	 * @Version 0.1
	 * @Description:转换地址为短地址
	 */
	if(!isset($_SESSION)){
		session_start();
	}
	include_once('../lib/config.php');
	
	$urls = array();
	$get_long_urls = array();

	/////////////////////////////////////////////////////////////////////////
	 function GooshortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );
 
        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );
 
        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);
 
        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
 
        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
 
        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);
 
        // decode and return the JSON response
		$response = json_decode($result, true);
        return  $response['id'];
    }
	
	function otherShortenUrl($get_api,$longUrl)
	{
		$curl = curl_init();
		$url = $get_api.rawurlencode($longUrl);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($curl);
		curl_close($curl);
		return $data;
	}
	function shortenUrl($longUrl)
	{
		switch(SHORTENER)
		{
			case 'Goo.gl' :
			{
				return GooshortenUrl($longUrl);
			}
			case 'is.gd' :
			{
				return otherShortenUrl('http://is.gd/api.php?longurl=',$longUrl);
			}
			case 'zi.mu' :
			{
				return otherShortenUrl('http://zi.mu/api.php?format=simple&action=shorturl&url=',$longUrl);
			}
		}
	}
	///////////////////////////////////////////////////////////////////////////
	$long_urls = substr($_POST['long_urls'],0,-1);
	$urls = explode("|",$long_urls);
	$short_urls = "";
	$long_urls_len = count($urls);

	for($i=0;$i<$long_urls_len;$i++){
	/*
		$curl = curl_init();
		$url = $get_api.rawurlencode($urls[$i]);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($curl);
		curl_close($curl);
		*/
		$data = shortenUrl($urls[$i]);
		$short_urls .= $data.'|'.$urls[$i].'^';
	}
	echo substr($short_urls,0,-1);
?>
